// done
#include "utils/logWriter.hpp"
#include <memory>
#include <cassert>
#include <cstdarg>
#include <ctime>
#include <cstdio>
#include <cstdlib>
/**
 * @description: LogWriter构造函数
 * @param {
 * const char* path 文件名
 * }
 * @return {void}
 * @src: logWriter.hpp
 */
LogWriter::LogWriter(const char* path)
{
  fp = fopen(path, "w+");
  if (fp == nullptr)
  {
    fputs("fopen error\n", stderr);
    assert(fp != nullptr);
  }
}
/**
 * @description: LogWriter析构函数
 * @param {void}
 * @return {void}
 * @src: logWriter.hpp
 */
LogWriter::~LogWriter()
{
  if (fp != nullptr)
  {
    fclose(fp);
    fp = nullptr;
  }
}
/**
 * @description: add timestamp
 * @param {
 * char* buffer
 * }
 * @return {int}
 * @src: LogWriter.hpp
 */
int LogWriter::preMark(char* buffer)
{
  time_t now;
  now = time(&now);
  struct tm vtm = *localtime(&now);
  return snprintf(buffer, LOG_BUFFER_SIZE, "%04d-%02d-%02d %02d:%02d:%02d ",
  vtm.tm_year+1900, vtm.tm_mon, vtm.tm_mday, vtm.tm_hour, vtm.tm_min, vtm.tm_sec);
}
/**
 * @description: timestamp write
 * @param {
 * const char* format,
 * ...
 * }
 * @return {bool}
 * @src: LogWriter.hpp
 */
bool LogWriter::writeTimestamp(const char* format, ...)
{
  if (fp == nullptr)
    return false;
  int nsize = 0;
  int prelen = 0;
  char* str = m_buffer;
  prelen = preMark(str);
  str += prelen;
  va_list args;
  va_start(args, format);
  nsize = snprintf(str, LOG_BUFFER_SIZE - prelen, format, args);
  va_end(args);
  fprintf(fp, "%s\n", m_buffer);
  fflush(fp);
  return true;
}
/**
 * @description: write
 * @param {
 * const char* format,
 * ...
 * }
 * @return {bool}
 * @src: LogWriter.hpp
 */
bool LogWriter::write(const char* format, ...)
{
  if (fp == nullptr)
    return false;
  int nsize = 0;
  char* str = m_buffer;
  va_list args;
  va_start(args, format);
  double variable = va_arg(args, double);
  nsize = snprintf(str, LOG_BUFFER_SIZE, format, variable);
  // printf("%s\n", str);
  va_end(args);
  fprintf(fp, "%s\n", m_buffer);
  fflush(fp);
  return true;
}